#! /bin/bash
# Submits a job to the next node in $PBS_NODEFILE

export POPC_BATCH=pbs
args=""
prog=""
current_node="local"

if [ "X$PBS_NODEFILE" = "X" ]; then
        echo "Error : \$PBS_NODEFILE not set : popcobjrun.pbs must only be used in a batch environment"
        exit -1
fi

if [ "X$POPC_RSH" = "X" ]; then
	POPC_RSH="/usr/bin/ssh"
fi

for arg in $* ; do
    if [ `echo "$arg"|grep "^\-batch-node="` ]; then
      current_node=`echo $arg|sed s/-batch-node=//`
    elif [ "X${prog}" = "X" ]; then
      prog=$arg
    else
      args="$args $arg"
    fi
done

if [ "$current_node" = "local" ]; then
  # Execute job locally with the standard command
  # echo "$0 executes : $prog -batch=pbs $args &"
  $prog -batch=pbs $args &
else

  # Find the next node and execute the job
  #nodes=`cat $PBS_NODEFILE`
  nbnodes=`cat $PBS_NODEFILE|wc -l`
  
  current_node=`expr $current_node % $nbnodes`
  current_node=`expr $current_node + 1`
  current_node_name=`cat $PBS_NODEFILE|sed -n "${current_node}p"`
  
  #echo "$0 executes : ssh $current_node_name $prog -batch=pbs $args &"
  $POPC_RSH $current_node_name $prog -batch=pbs $args &
  
fi